<template>
  <div id="dispose">
    <v-title title="汽车管理看板配置"></v-title>

    <!-- <v-condition :isMultiple="true"></v-condition>-->

    <div style="position: relative;margin-bottom: 20px;text-align: right;margin-right: 50px;">      
      <el-button class="loader" type="warning" @click="getExcel">下载配置模板</el-button>
      <el-upload
        class="upload-demo"
        :action="url"
        name="excel"
        ref="upLoadFile"
        :before-upload="beforeAvatarUpload"
        accept=".xlsx,.xls"
        :limit="999"
        :on-error="erroring"
        :on-success="handleSuccess"
        :on-remove="handleRemove"
        :file-list="fileList"
        :http-request="handUploadFile"
        >
        <el-button size="small" type="success">上传Excel数据</el-button>
        <div slot="tip" class="el-upload__tip">只能上传excel文件</div>
      </el-upload>
    </div>

   <!-- <el-button class="marT" type="primary">数据更新情况</el-button>
    <div class="table">
      <el-table
        class="marT"          
        :border="true"
        :header-cell-style="{background: 'rgb(50, 65, 90)'}"
        :data="base.slice((baseCurrent-1)*baseSize, baseCurrent*baseSize)" 
        fit                     
        style="width: 100%"
        >
          <el-table-column
            label="项目"
            align="center"
            prop="project_name">     
          </el-table-column>          
          <el-table-column
            label="项目风险管理"
            align="center"
            > 
            <template slot-scope="scope">
              <v-button :statusObj="scope.row.risk_close_rate"></v-button>
            </template>
          </el-table-column>
          <el-table-column
            label="里程碑阶段状态"
            align="center">      
            <template slot-scope="scope">
              <v-button :statusObj="scope.row.milestone_status"></v-button>
            </template>
          </el-table-column>

          <el-table-column
            label="项目工程进度"
            align="center"
          >
            <template slot-scope="scope">
              <v-button :statusObj="scope.row.project_progress"></v-button>
            </template> 
          </el-table-column>
          <el-table-column
            label="工程质量"
            align="center"
          > 
            <template slot-scope="scope">
              <v-button :statusObj="scope.row.project_quality"></v-button>
            </template>
          </el-table-column>
          <el-table-column
            label="成本"
            align="center"
          > 
            <template slot-scope="scope">
              <v-button :statusObj="scope.row.cost"></v-button>
            </template>
          </el-table-column>
          <el-table-column
            label="商务风险"
            align="center"
          > 
            <template slot-scope="scope">
              <v-button :statusObj="scope.row.commerce_risk"></v-button>
            </template>
          </el-table-column>

          <el-table-column
            label="BU自评"
            align="center"
          > 
            <template slot-scope="scope">
              <v-button :statusObj="scope.row.self_assessment"></v-button>
            </template>
          </el-table-column>

          <el-table-column
            label="客户满意度"
            align="center"
          > 
            <template slot-scope="scope">
              <v-button :statusObj="scope.row.customer_satisfaction"></v-button>
            </template>
          </el-table-column>

          <el-table-column
            label="更新人"
            align="center"
          > 
            <template slot-scope="scope">
              <div>{{ scope.row.operator }}</div>
            </template>
          </el-table-column>

          <el-table-column
            label="最近更新时间"
            align="center"
          > 
            <template slot-scope="scope">
              <div>{{ scope.row.update_time }}</div>
            </template>
          </el-table-column>

          <el-table-column
            label="分类"
            align="center"
          > 
            <template slot-scope="scope">
              <div @click="dialogResult(scope.row.project_id)" class="details">
                查看详情
              </div>
            </template>
          </el-table-column>
      </el-table>
      <el-pagination class="marT"
        v-show="baseTotal > 10"
        background  
        :page-size="baseSize"                                   
        @current-change="baseCurrentChange"
        :current-page="baseCurrent"
        @size-change="baseCurrentSize"                              
        layout="total, sizes, prev, pager, next, jumper"
        style="text-align: left"
        :total="baseTotal">
      </el-pagination>
    </div> -->

    <div class="btn-group marT titleRelative">
      <el-button class="title" type="primary">事业群配置</el-button>
      <el-button class="button" @click="toEdit" v-show="!edit" type="primary" round>编辑配置</el-button>
      <el-button class="button" @click="saveResult" v-show="edit" type="success" round>保存提交</el-button>
    </div>
    <div class="table">
      <el-table
        class="marT"          
        :border="true"
        :header-cell-style="{background:'rgb(50, 65, 90)'}"
        :data="list"                      
        style="width: 100%"
        >
          <el-table-column
            label="数据维度"
            align="center"
            prop="dimension">     
          </el-table-column>

          <el-table-column
            label="负责人(owner)"
            align="center"
            >     
            <template slot-scope="scope">
              <div v-if="!edit">
                {{ generate(scope.row.owner).join(',') }}                
              </div>
              <div v-else>
                <el-select
                  v-model="scope.row.ownerList"
                  multiple
                  filterable
                  remote                  
                  placeholder="请输入owner"
                  :remote-method="remoteMethod"
                  :loading="loading"
                  @blur="blur" 
                  @change="change(scope.$index, $event)"               
                  >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    >
                      <span style="float: left">{{ item.label }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
                  </el-option>
                </el-select>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            label="更新频率"
            align="center"
            >    
            <template slot-scope="scope">
              <div v-if="!edit">{{ toDate(scope.row.update_freq) }}</div>
              <div v-else>
                <el-select v-model="scope.row.update_freq" placeholder="请选择更新频率">
                  <el-option
                    v-for="item in rateOptions"
                    :key="item.label"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            label="数据时间"
            align="center"
            prop="data_time">     
          </el-table-column>

          <el-table-column
            label="数据来源"
            align="center"
            prop="data_source">     
          </el-table-column>

          <!-- <el-table-column
            label="最新更新时间"
            align="center"
            prop="update_time">     
          </el-table-column> -->
      </el-table>
    </div>

    <!-- <el-dialog width="80%" title="更新详情" :visible.sync="dialogTableVisible">
      <v-dialog
        v-if="dialogTableVisible"
        id="dialog"
        :tableList="dialogData" 
        :tableListLabel="tableListLabel"
      ></v-dialog>
    </el-dialog> -->
  </div>
</template>

<script>
  import VTitle from '@/views/sys/internetThings/title'
  import VCondition from '@/views/data/carDispose/group'
  import { mapState } from 'vuex'
  import http from '@/views/sys/axios'
  // import VDialog from '@/views/qa/dialog'
  // import VButton from './button'

  export default {
    name: 'Dispose',
    components: {
      VTitle,
      VCondition,
      // VDialog,
      // VButton
    },
    data() {
      return {
        list: [],
        // base: [],
        url: `/api/data_summary/car/project/file/upload`,
        // baseCurrent: 1,
        // baseTotal: 0,
        // baseSize: 10,
        options: [],
        fileStatus: true,
        fileList: [],
        rateOptions: [
          {
            value: 1,
            label: '每周一'
          },
          {
            value: 2,
            label: '每周二'
          },
          {
            value: 3,
            label: '每周三'
          },
          {
            value: 4,
            label: '每周四'
          },
          {
            value: 5,
            label: '每周五'
          },
          {
            value: 10,
            label: '每月'
          }
        ],
        cache: [],        
        edit: false,
        loading: false
        // dialogTableVisible: false,
        // dialogData: [],
        // tableListLabel: [
        //   {
        //       label: '项目',
        //       param: 'project_name',
        //       align: 'center'
        //   },
        //   {
        //       label: '更新模块',
        //       param: 'dimension',
        //       align: 'center'
        //   }, 
        //   {
        //       label: '更新项',
        //       param: 'examine_item',
        //       align: 'center'
        //   },
        //   {
        //       label: '修改者',
        //       param: 'operator',
        //       align: 'center'
        //   },
        //   {
        //       label: '修改日志',
        //       param: 'operator_log',
        //       align: 'center'
        //   },
        //   {
        //       label: '更新时间',
        //       param: 'create_time',
        //       align: 'center'
        //   }                                           
        // ]
      }
    },
    computed: {
      ...mapState({
        dispose: state => state.conditions.dispose
      })
    },
    mounted() {
      this.getTableResult()
      // if(this.dispose.projectIdList.length) {
      //   this.getLookResult()
      // }
    },
    methods: {
      toEdit() {
        this.edit = true
      },
      getExcel() {
        http.get(`${process.env.VUE_APP_KANBAN_HOST}/api/data_summary/car/project/file/upload`, { responseType: 'blob' })
        .then(res => {
          const { data, code } = res
          
          if(code === 200) {
            let blob = new Blob([data], {type: 'application/vnd.ms-excel'})
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = URL.createObjectURL(blob)
            link.setAttribute('download', '汽车管理看板数据模板.xlsx')
            document.body.appendChild(link)
            link.click()
            URL.revokeObjectURL(link.href)
            document.body.removeChild(link)
          } else {
            this.$message.error('下载出错了!'); 
          }
        }).catch(err => {
          const { data } = err
          
          if(data) {
            let blob = new Blob([data], {type: 'application/vnd.ms-excel'})
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = URL.createObjectURL(blob)
            link.setAttribute('download', '汽车管理看板数据模板.xlsx')
            document.body.appendChild(link)
            link.click()
            URL.revokeObjectURL(link.href)
            document.body.removeChild(link)
          } else {
            this.$message.error('下载出错了!'); 
          }          
        })
      },
      async handUploadFile(content) {
        const { file } = content              
        let formData = new FormData();     
        formData.append('file',content.file);
        formData.append('name',file.name);
        http.post(content.action, formData).then(res => {
          if(res.code == 200) {
            content.onSuccess('文件上传成功')
          } else {
            content.onError(`文件上传失败,${res.msg}`)
          }
        }).catch(err => {
          throw err
        })
      },
      handleSuccess(res) {
        if(res) {
          this.$message({
            message: res,
            type: 'success'
          });
        }      
      },
      erroring(err) {
        if(err) {
          this.$message({
            message: err,
            type: 'error'
          });
        }
      },
      handleRemove(file) {
        this.fileList = []
      },
      beforeAvatarUpload(file) {
        let size = file.size / 1024
        this.fileStatus = true
        
        if (size > 50000) {
          this.$message({
            message: '导入的Excel表不能大于50M!',
            type: 'error'
          });
          this.fileStatus = false
          return
        }

        let name = file.name;
        let fileName = name.substring(name.lastIndexOf(".") + 1).toLowerCase();
        if (fileName != "xlsx" && fileName != "xls") {
          this.$message({
            message: '请选择正确得Excel格式文件上传!',
            type: 'error'
          }); 
          this.fileStatus = false
          return
        }   
      },
      toDate(num) {
        num = Number(num)
        switch (num) {
          case 1:
            return '每周一';
            break;
          case 2:
            return '每周二';
            break;
          case 3:
            return '每周三';
            break;
          case 4:
            return '每周四';
            break;
          case 5:
            return '每周五';
            break;
          case 10:
            return '每月';
            break;
          default:
            return '';
            break;
        } 
      },
      // baseCurrentChange(val) {
      //   this.baseCurrent = val
      // },
      // baseCurrentSize(val) {
      //   this.baseSize = val
      // },
      change(index, val) {
        const obj = this.cache.filter(item => item.value === val[val.length - 1])
        const owner = [...this.list[index].owner, ...obj]
        this.$set(this.list[index], 'owner', owner)
      },
      generate(arr) {
        if(arr.length) {
          const list = arr.map(item => item.label)
          return list
        } else {
          return []
        }
      },
      blur() {
        this.options = []
      },
      async remoteMethod(query) {
        if (query !== '') {
          this.loading = true;
          this.options = []
          this.getStateResult(query)
        } else {
          this.options = [];
        }
      },
      // showDialog(id) {
      //   return http.get(`/api/data_summary/car/project/record?projectId=${id}`)
      // },
      // async dialogResult(id) {
      //   try {
      //     this.dialogTableVisible = true
      //     const { code, result } = await this.showDialog(id)
      //     if(code === 200) {
      //       this.dialogData = result
      //     }
      //   } catch(err) {
      //     throw new Error(err)
      //   }
      // },
      // getLook() {
      //   let data = {}  
      //   data.projects = this.dispose.projectIdList   
      //   return http.post(`/api/data_summary/car/project/operate/info`, data)
      // },
      // async getLookResult() {
      //   try {
      //     const { code, result } = await this.getLook()
      //     if(code === 200) {
      //       this.base = result
      //       this.baseTotal = this.base.length
      //     }
      //   } catch(err) {
      //     throw new Error(err)
      //   }
      // },
      getStates(name) {
        return http.get(`/api/account/user/query?name=${name}`)
      },
      async getStateResult(name) {
        try {
          const { code, user_list } = await this.getStates(name)
          if(code === 200) {
            this.loading = false
            this.options = user_list
            this.cache = user_list
          }
        } catch (err) {
          throw new Error(err)
        }
      },
      getTable() {
        return http.get(`/api/data_summary/car/project/config`)
      },
      async getTableResult() {
        try {
          const { code, result } = await this.getTable()
          if(code === 200) {
            this.list = result
            this.list = this.list.map(item => {
              const ownerList = item.owner.map(ow => ow.label)
              return {
                ...item,
                ownerList
              }
            })
            // let arr = this.list
          }
        } catch (err) {
          throw new Error(err)
        }
      },
      save() {
        this.list.forEach(item => {
          item.owner = item.owner.filter(ow => {
            const index = item.ownerList.findIndex(idx => ow.label == idx || ow.value == idx)
            if(index == -1) {
              return false
            }
            return true
          })
        })
        console.log(this.list)
        let data = this.list
        return http.post(`/api/data_summary/car/project/config`, data)
      },
      async saveResult() {
        try {
          const { code, msg } = await this.save()
          if(code === 200) {
            this.$message({
              showClose: true,
              message: '保存成功!',
              type: 'success'
            });
            this.edit = false
            this.getTableResult()
          } else {
            this.$message({
              showClose: true,
              message: msg,
              type: 'error'
            });
          }
        } catch(err) {
          this.edit = false
          throw new Error(err)
        }
      }
    }
    // watch: {
    //   dispose: {
    //     handler: function(newVal) {
    //       if(newVal) {
    //         this.getLookResult()
    //       }
    //     },
    //     deep: true
    //   },
    //   dialogTableVisible(newVal) {
    //     if(!newVal) {
    //       this.dialogData = []
    //     }
    //   }
    // }
  }
</script>

<style lang="scss" scoped>
  @import '../../../assets/common/common.scss';
  /deep/ .el-table thead {
    color: #fff;
  }
  /deep/ .el-table th.gutter{
    display: table-cell!important;
  }
  #dialog >>> .el-table thead{
    color: #909399;
  }
  .loader{
    margin: 15px 0px;
    position: absolute;
    right: 175px;
    top: -16px;
  }
  #dispose{
    padding: 32px;
    background-color: rgb(240, 242, 245);
    position: relative;
    .btn-group{
      text-align: right;
      position: relative;
      .title{
        position: absolute;
        left: 0;
      }
    }
    .details{
      cursor: pointer;
      color: rgb(50, 65, 90);
      text-decoration: underline;
    }
  }
  .marT{
      margin-top: 20px;
  }
</style>